
#include "stdafx.h"
#include "fileio.h"

#include <windows.h>

#if 0
osFILE_DISK::osFILE_DISK(void)
   : offset(0)
   , handle(NULL)
   , buffer(NULL)
   , allocated(0)
   , bufferAvail(0)
   , bufferOffset(0)
   , isWritable(false)
{
}

void osFILE_DISK::AllocateBuffer(int size)
{
   bufferAvail    = 0;

   if (size == allocated) {
      return ;
   }

   ASSERT(size > 0);

   buffer         = (BYTE *)realloc(buffer, size);
   bufferCur      = buffer;
   allocated      = size;
}

bool osFILE_DISK::OpenRead(const char * filename, int bufferSize /* = 4096 */)
{
   AllocateBuffer(bufferSize);

   isWritable = false;
   offset = 0;

   HANDLE file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
   if (file == INVALID_HANDLE_VALUE) {
      return false;
   }

   handle = file;

   return true;
}

bool osFILE_DISK::OpenWrite(const char * filename, int bufferSize /* = 4096 */)
{
   AllocateBuffer(bufferSize);

   offset = 0;

   HANDLE file = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
   if (file == INVALID_HANDLE_VALUE) {
      return false;
   }

   isWritable = true;
   handle = file;

   return true;
}

bool osFILE_DISK::OpenAppend(const char * filename, int bufferSize /* = 4096 */)
{
   AllocateBuffer(bufferSize);

   HANDLE file = CreateFile(filename, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);
   if (file == INVALID_HANDLE_VALUE) {
      return false;
   }

   offset = SetFilePointer(file, 0, NULL, FILE_END);

   isWritable = true;
   handle = file;

   return true;
}

int osFILE_DISK::Read(void * buf, int count, int elemSize /* = 1 */)
{
   BYTE * dst = (BYTE *)buf;
   int toCopy = count * elemSize;

   int copied = 0;

   if (bufferAvail > 0) {
      copied         = min(toCopy, bufferAvail);
      memcpy(dst, bufferCur, copied);
      dst            += copied;
      bufferCur      += copied;
      toCopy         -= copied;
      bufferAvail    -= copied;
   }

   // read directly
   if (toCopy > allocated) {
      DWORD readed = 0;
      ReadFile((HANDLE)handle, dst, toCopy, &readed, NULL);

      return copied + readed;
   }

   // read to buffer
   FillBuffer();
   // TODO: rest of file
}
#endif